package com.hemaapp.yjnh.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.uu.utils.uuUtils;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.view.RoundedImageView;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.FarmerOrder;
import com.hemaapp.yjnh.bean.Order;
import com.hemaapp.yjnh.bean.Order.BillChild;
import com.hemaapp.yjnh.bean.OrderDetail;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.utils.ImageUtils;

import java.net.MalformedURLException;
import java.net.URL;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import xtom.frame.image.load.XtomImageTask;
import xtom.frame.image.load.XtomImageTask.Size;
import xtom.frame.util.XtomToastUtil;

/**
 * 田家农货订单详情
 *
 * @author GuiyouZhang
 */
public class FarmerOrderDetailActivity extends BaseActivity implements OnClickListener {

    @Bind(R.id.title_left_btn)
    ImageButton titleLeftBtn;
    @Bind(R.id.title_right_btn)
    Button titleRightBtn;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.tv_client_name)
    TextView tvClientName;
    @Bind(R.id.tv_mobile)
    TextView tvMobile;
    @Bind(R.id.tv_address)
    TextView tvAddress;
    @Bind(R.id.tv_order_sn)
    TextView tvOrderSn;
    @Bind(R.id.layout_goods)
    LinearLayout layoutGoods;
    @Bind(R.id.tv_cash_stamp)
    TextView tvCashStamp;
    @Bind(R.id.tv_freight)
    TextView tvFreight;
    @Bind(R.id.tv_money)
    TextView tvMoney;
    @Bind(R.id.iv_edit_express)
    ImageView ivEditExpress;
    @Bind(R.id.tv_order_num)
    TextView tvOrderNum;
    @Bind(R.id.tv_order_time)
    TextView tvOrderTime;
    @Bind(R.id.tv_express_name)
    TextView tvExpressName;
    @Bind(R.id.tv_express_num)
    TextView tvExpressNum;
    @Bind(R.id.tv_order_status)
    TextView tvOrderStatus;
    @Bind(R.id.tv_cancel)
    TextView tvCancel;
    @Bind(R.id.tv_agree)
    TextView tvAgree;
    @Bind(R.id.tv_send)
    TextView tvSend;
    @Bind(R.id.layout_bottom)
    LinearLayout layoutBottom;

    private OrderDetail mOrder;//当前的订单
    private User user;
    private HemaButtonDialog hbDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_seller_order_detail);
        ButterKnife.bind(this);
        user = getApplicationContext().getUser();
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void getExras() {
        String orderId = mIntent.getStringExtra("order_id");
        getNetWorker().getOrderDetail(user.getToken(), orderId);
    }

    @Override
    protected void setListener() {
        titleText.setText("订单详情");
        titleRightBtn.setVisibility(View.GONE);
    }

    @OnClick({R.id.title_left_btn, R.id.tv_cancel, R.id.tv_agree, R.id.tv_send, R.id.iv_edit_express})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.tv_cancel:
                refuseReturn();
                break;
            case R.id.tv_agree:
                agreeReturn();
                break;
            case R.id.tv_send:
                deliverGoods();
                break;
            case R.id.iv_edit_express:
                deliverGoods();
                break;
        }
    }

    private void setDatas(){
        //设置地址
        tvClientName.setText(mOrder.getConsignee());
        tvMobile.setText(mOrder.getPhone());
        tvAddress.setText(mOrder.getAddress());
        //订单信息
        double goodsFee = 0.0;
        double stampFee = 0.0;
        try {
            goodsFee = Double.parseDouble(mOrder.getGoods_fee());
            stampFee = Double.parseDouble(mOrder.getScore_fee());
        }catch (Exception e) {
            e.printStackTrace();
        }
        tvCashStamp.setText("¥"+ uuUtils.formatAfterDot2(goodsFee-stampFee+"")+" + ");
        BaseUtil.addStampSign(mContext, tvCashStamp, R.drawable.food_stamp_grey);
        tvCashStamp.append(uuUtils.formatAfterDot2(mOrder.getScore_fee())+"粮票");
        tvFreight.setText("¥"+ uuUtils.formatAfterDot2(mOrder.getShipping_fee()));
        tvMoney.setText("¥"+uuUtils.formatAfterDot2(mOrder.getTotal_fee()));
        tvOrderNum.setText("订单号码："+mOrder.getBill_sn());
        tvOrderTime.setText("下单时间："+mOrder.getRegdate());
        tvExpressName.setText("快递名称："+BaseUtil.transNull(mOrder.getShipping_name()));
        tvExpressNum.setText("快递单号："+BaseUtil.transNull(mOrder.getShipping_num()));
        setOrderStatus();
        if (!isNull(mOrder.getShipping_name()) && mOrder.getTradetype().equals("2"))//只有待收货的时候才能显示
            ivEditExpress.setVisibility(View.VISIBLE);
        else
            ivEditExpress.setVisibility(View.GONE);
        //动态添加多个商品
        if (layoutGoods.getChildCount() != 0) {
            layoutGoods.removeAllViews();
        }
        for (int i = 0; i < mOrder.getChildItems().size(); i++) {
            OrderDetail.ChildItemsBean child = mOrder.getChildItems().get(i);
            View view = LayoutInflater.from(mContext).inflate(
                    R.layout.item_order_goods, null);
            ItemViewHolder ivHolder = new ItemViewHolder();
            itemFindView(view, ivHolder);
            setItem(i, child, view, ivHolder);
            view.setTag(mOrder.getChildItems().get(i).getBlog_id());
            view.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    String blog_id = (String) v.getTag();
                    // 先根据商品属性自己判断
                    Intent intent = new Intent(mContext, FarmerCropDetailActivity.class);
                    intent.putExtra("blog_id", blog_id);
                    mContext.startActivity(intent);
                }
            });
        }
    }

    private class ItemViewHolder {
        private ImageView img;
        private TextView name;
        private TextView price;
        private TextView amount;
        TextView tvCommit;
        TextView tvAfterSale;
        TextView tvHint;
        View div;
    }

    /**一个订单中的多个商品
     * @param view
     * @param ivHolder
     */
    private void itemFindView(View view, ItemViewHolder ivHolder) {
        ivHolder.img = (ImageView) view.findViewById(R.id.img);
        ivHolder.name = (TextView) view.findViewById(R.id.good_name);
        ivHolder.price = (TextView) view.findViewById(R.id.price);
        ivHolder.amount = (TextView) view.findViewById(R.id.count);
        ivHolder.tvCommit = (TextView) view.findViewById(R.id.tv_commit);
        ivHolder.tvAfterSale = (TextView) view.findViewById(R.id.tv_aftersale);
        ivHolder.tvHint = (TextView) view.findViewById(R.id.tv_hint);
        ivHolder.div = view.findViewById(R.id.divider);
    }

    private void setItem(int i, OrderDetail.ChildItemsBean child, View view, ItemViewHolder ivHolder) {
        ImageUtils.loadSmalImage(mContext, child.getImgurl(), ivHolder.img);
        ivHolder.name.setText(child.getName());
        ivHolder.price.setText("¥" + uuUtils.formatAfterDot2(child.getPrice()));
        ivHolder.amount.setText("x" + child.getBuycount());
        if (i == mOrder.getChildItems().size() - 1) {
            ivHolder.div.setVisibility(View.GONE);
        } else {
            ivHolder.div.setVisibility(View.VISIBLE);
        }
        layoutGoods.addView(view);
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case ORDER_SAVEOPERATE:
            case ORDER_GET:
                showProgressDialog("请稍候");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case ORDER_SAVEOPERATE:
            case ORDER_GET:
                cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case ORDER_SAVEOPERATE:
                XtomToastUtil.showShortToast(mContext, "操作成功");
                EventBusMsg msg = new EventBusMsg();
                msg.setType(EventBusConfig.UPDATE_ORDER);
                EventBus.getDefault().post(msg);
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        finish();
                    }
                }, 1000);
                break;
            case ORDER_GET:
                HemaArrayResult<OrderDetail> bResult = (HemaArrayResult<OrderDetail>) baseResult;
                mOrder = bResult.getObjects().get(0);
                setDatas();
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case ORDER_SAVEOPERATE:
                XtomToastUtil.showShortToast(mContext, "订单操作失败,"+baseResult.getMsg());
                break;
            case ORDER_GET:
                XtomToastUtil.showShortToast(mContext, "获取详情失败,"+baseResult.getMsg());
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case ORDER_SAVEOPERATE:
                XtomToastUtil.showShortToast(mContext, "订单操作失败, 请稍后再试");
                break;
            case ORDER_GET:
                XtomToastUtil.showShortToast(mContext, "获取详情失败, 请稍后再试");
                break;
        }
    }

    /**
     * 获取订单的状态
     *
     * @return
     */
    private void setOrderStatus() {
        //订单状态	1：有效 2：已删除
        if (mOrder.getStatetype().equals("2")) {
            tvOrderStatus.setText("订单状态：已关闭");
            setBottomButton(new int[]{View.GONE, View.GONE, View.GONE, View.GONE});
        }
        //交易状态	0 未付款 1: 已付款待发货 2 待收货 3 已收货待评价 4 已评价交易成功
        if (mOrder.getTradetype().equals("0")) {
            tvOrderStatus.setText("订单状态：待付款");
            setBottomButton(new int[]{View.GONE, View.GONE, View.GONE, View.GONE});
        }else if (mOrder.getTradetype().equals("1")) {
            tvOrderStatus.setText("订单状态：发货");
            setBottomButton(new int[]{View.VISIBLE, View.GONE, View.GONE, View.VISIBLE});
        }else if (mOrder.getTradetype().equals("2")) {
            tvOrderStatus.setText("订单状态：待收货");
            ivEditExpress.setClickable(false);
            setBottomButton(new int[]{View.GONE, View.GONE, View.GONE, View.GONE});
        }else if (mOrder.getTradetype().equals("3")) {
            tvOrderStatus.setText("订单状态：待评价");
            setBottomButton(new int[]{View.GONE, View.GONE, View.GONE, View.GONE});
        }else if (mOrder.getTradetype().equals("4")) {
            tvOrderStatus.setText("订单状态：交易成功");
            setBottomButton(new int[]{View.GONE, View.GONE, View.GONE, View.GONE});
        }
    }

    /**
     * @param visibility
     * 底部按钮的顺序依次为：
     * layoutBottom、拒绝退货、同意退货、发货
     */
    public void setBottomButton(int[] visibility) {
        layoutBottom.setVisibility(visibility[0]);
        if (visibility[0] == View.VISIBLE) {
            tvCancel.setVisibility(visibility[1]);
            tvAgree.setVisibility(visibility[2]);
            tvSend.setVisibility(visibility[3]);
        }
    }

    public void agreeReturn() {
        HemaButtonDialog hbDialog = new HemaButtonDialog(mContext);
        hbDialog.setText("确定同意买家的售后吗？");
        hbDialog.setLeftButtonText("取消");
        hbDialog.setRightButtonText("确定");
        hbDialog.setRightButtonTextColor(getResources().getColor(R.color.theme_orange));
        hbDialog.setButtonListener(new HemaButtonDialog.OnButtonListener() {

            @Override
            public void onRightButtonClick(HemaButtonDialog dialog) {
                dialog.cancel();
                getNetWorker().orderSaveoperate(user.getToken(), mOrder.getId(), "10", "无",
                        "无", "无", "无");
            }

            @Override
            public void onLeftButtonClick(HemaButtonDialog dialog) {
                dialog.cancel();
            }
        });
    }

    public void refuseReturn() {
        HemaButtonDialog hbDialog = new HemaButtonDialog(mContext);
        hbDialog.setText("确定拒绝买家的售后吗？");
        hbDialog.setLeftButtonText("取消");
        hbDialog.setRightButtonText("确定");
        hbDialog.setRightButtonTextColor(getResources().getColor(R.color.theme_orange));
        hbDialog.setButtonListener(new HemaButtonDialog.OnButtonListener() {

            @Override
            public void onRightButtonClick(HemaButtonDialog dialog) {
                dialog.cancel();
                getNetWorker().orderSaveoperate(user.getToken(), mOrder.getId(), "11", "无",
                        "无", "无", "无");
            }

            @Override
            public void onLeftButtonClick(HemaButtonDialog dialog) {
                dialog.cancel();
            }
        });
    }

    /**
     * 卖家对某个订单进行发货
     *
     */
    public void deliverGoods() {
        View dialogview = getLayoutInflater().inflate(R.layout.dialog_deliver_goods_info, null);
        final Dialog dialog = new Dialog(mContext, R.style.CustomizeDialogStyle);
        dialog.setContentView(dialogview);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(true);
        final EditText etName = (EditText) dialogview.findViewById(R.id.et_express_name);
        final EditText etNum = (EditText) dialogview.findViewById(R.id.et_express_num);
        TextView tvCancel = (TextView) dialogview.findViewById(R.id.tv_cancel);
        TextView tvOk = (TextView) dialogview.findViewById(R.id.tv_ok);
        tvCancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.cancel();
            }
        });
        tvOk.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String expressName = etName.getText().toString();
                String expressNum = etNum.getText().toString();
                if (expressName.isEmpty()) {
                    XtomToastUtil.showShortToast(mContext, "快递公司名称不能为空!");
                    return;
                }
                if (expressNum.isEmpty()) {
                    XtomToastUtil.showShortToast(mContext, "快递单号不能为空!");
                    return;
                }
                dialog.cancel();
                getNetWorker().orderSaveoperate(user.getToken(), mOrder.getId(), "4", "无",
                        "无", expressName, expressNum);
            }
        });
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.CENTER);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.x = 0;
        lp.y = 0;
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        dialogWindow.setAttributes(lp);
        dialog.show();
    }
}
